package com.ssf.hsdtouch.extension.util;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import com.ssf.hsdtouch.extension.entity.FileObj;
import com.ssf.hsdtouch.extension.fragment.PicFragment;
import com.ssf.hsdtouch.extension.fragment.VideoViewFragment;
import com.ssf.hsdtouch.extension.util.ExtensionUtil.FileType;

public class PSAdapter extends FragmentStatePagerAdapter {
	private ArrayList<FileObj> data;
	private List<Fragment> fragmentdata;
	int mCount = 0;
	FragmentManager fm;

	public PSAdapter(FragmentManager fm) {
		super(fm);
		this.fm = fm;
		data = new ArrayList<FileObj>();
		fragmentdata = new ArrayList<Fragment>();
		initFrags();
		mCount = data.size();
	}

	public PSAdapter(FragmentManager fm, ArrayList<FileObj> data) {
		super(fm);
		this.fm = fm;
		this.data = data;
		fragmentdata = new ArrayList<Fragment>();
		initFrags();
		mCount = data.size();
	}

	private void initFrags() {
		for (int i = 0; i < data.size(); i++) {
			FileObj obj = data.get(i);
			if (obj.getType() == FileType.IMAGE) {
				PicFragment f = new PicFragment();
				fragmentdata.add(f);
			} else if (obj.getType() == FileType.VIDEO) {
				VideoViewFragment f = new VideoViewFragment();
				fragmentdata.add(f);
			}
		}
	}

	public Fragment getFragmentdata(int index) {
		return fragmentdata.get(index);
	}

	public int getFragmentCount() {
		if (fragmentdata != null) {
			return fragmentdata.size();
		}
		return 0;
	}

	public void setData(ArrayList<FileObj> data) {
		this.data = data;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		return super.instantiateItem(container, position);
	}

	@Override
	public Fragment getItem(int index) {
		if (index >= data.size()) {
			int newPosition = index % data.size();
			index = newPosition;
			mCount++;
		}
		if (index < 0) {
			index = -index;
			mCount--;
		}
		FileObj obj = data.get(index);
		Bundle b = new Bundle();
		b.putSerializable("file", obj);
		Fragment f = getFragmentdata(index);
		f.setArguments(b);
		return f;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		if (position >= data.size()) {
			int newPosition = position % data.size();
			position = newPosition;
		}
		if (position < 0) {
			position = -position;
		}
		super.destroyItem(container, position, object);
	}

	@Override
	public int getCount() {
		return data.size();
	}

}
